package com.qiandw.myblog.exception;

import com.qiandw.common.result.MessageConstants;
import com.qiandw.common.result.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 全局异常处理
 *
 * @author KG
 */
@Slf4j
@ControllerAdvice({})
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error");
        return mav;
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public ModelAndView assertExceptionHandler(HttpServletRequest req, IllegalArgumentException e)
            throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("msg", e.getMessage());
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error/500");
        return mav;
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public Response myException(Exception e) {
        return handleException(MessageConstants.MSG_SYS_EXCEPTION, e);
    }

    private Response handleException(Map<String, String> msg, Exception exception) {
        Response resp = new Response();
        for (String key : msg.keySet()) {
            resp.setMsgCode(key);
            resp.setMsg(msg.get(key));
        }
        resp.setErrorDetail(exception.getMessage());
        return resp;
    }
}
